package com.glkj.vipsystem.modules.merchant.controller;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.glkj.vipsystem.common.utils.PageUtils;
import com.glkj.vipsystem.common.utils.Query;
import com.glkj.vipsystem.common.utils.R;
import com.glkj.vipsystem.common.validator.ValidatorUtils;
import com.glkj.vipsystem.common.validator.group.AddGroup;
import com.glkj.vipsystem.common.validator.group.UpdateGroup;
import com.glkj.vipsystem.entity.ao.CompanyAO;
import com.glkj.vipsystem.modules.sys.controller.AbstractController;
import com.glkj.vipsystem.service.ICompanyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 公司控制器
 *
 * @author LiMuchan
 */
@RestController
@RequestMapping("/merchant/company")
public class CompanyController extends AbstractController {

    @Resource
    private ICompanyService companyService;

    /**
     * 列表
     */
    @RequestMapping(value = "/list")
    @RequiresPermissions({"merchant:company:list"})
    public R list(@RequestParam Map<String, Object> params) {
        String companyName = (String) params.get("companyName");
        String companyAreaCode = (String) params.get("companyAreaCode");
        Page<CompanyAO> page = companyService.selectPage(
                new Query<CompanyAO>(params).getPage(),
                new EntityWrapper<CompanyAO>()
                        .setSqlSelect("*,(select count(*) from t_shop where company_id = t_company.id) as shop_num")
                        .orderBy("create_time desc")
                        .like(StringUtils.isNotBlank(companyName), "company_name", companyName)
                        .like(StringUtils.isNotBlank(companyAreaCode), "company_area_code", companyAreaCode)
        );
        return R.ok().put("page", new PageUtils(page));
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{id}")
    @RequiresPermissions({"merchant:company:list"})
    public R detail(@PathVariable("id") Integer id) {
        return R.ok().put("item", companyService.selectById(id));
    }

    /**
     * 检测公司是否存在
     */
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public R check(@RequestBody CompanyAO company) {
        CompanyAO companyAO = companyService.selectOne(
                new EntityWrapper<CompanyAO>()
                        .eq("company_name", company.getCompanyName())
                        .eq("manager_name", company.getManagerName())
                        .eq("manager_mobile", company.getManagerMobile())
                        .eq("status", 1)
        );
        if (companyAO == null) {
            return R.error("公司不存在或已禁用");
        }
        return R.ok();
    }

    /**
     * 保存新增
     */
    @RequestMapping(value = "/save")
    @RequiresPermissions({"merchant:company:save"})
    public R save(@RequestBody CompanyAO company) {
        ValidatorUtils.validateEntity(company, AddGroup.class);
        if (!company.getPassword().equals(company.getConfirmPassword())) {
            return R.error("两次密码不一致");
        }
        if (!Validator.isGeneral(company.getUsername(), 3, 15)) {
            return R.error("请填写3~15位的登录用户名,字母、数字、下划线组合");
        }
        if (!Validator.isGeneral(company.getPassword(), 6, 15)) {
            return R.error("请填写6~15位的登录密码,字母、数字、下划线组合");
        }
        companyService.save(company, getUserId());
        return R.ok();
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @RequiresPermissions({"merchant:company:update"})
    public R update(@RequestBody CompanyAO company) {
        ValidatorUtils.validateEntity(company, UpdateGroup.class);
        if (StringUtils.isNotBlank(company.getPassword()) && !company.getPassword().equals(company.getConfirmPassword())) {
            return R.error("两次密码不一致");
        }
        if (StringUtils.isNotBlank(company.getPassword()) && !Validator.isGeneral(company.getPassword(), 6, 15)) {
            return R.error("请填写6~15位的登录密码,字母、数字、下划线组合");
        }
        companyService.update(company);
        return R.ok();
    }

    /**
     * 修改公司状态
     */
    @RequestMapping(value = "/updateStatus")
    @RequiresPermissions({"merchant:company:update"})
    public R updateStatus(@RequestBody CompanyAO company) {
        companyService.update(company);
        return R.ok();
    }

    /**
     * 调整公司店铺、店铺员工数量
     */
    @RequestMapping(value = "/update-num")
    @RequiresPermissions({"merchant:company:shop:employee:num"})
    public R updateNum(@RequestBody CompanyAO company) {
        if (company == null || company.getId() == null) {
            return R.error("请选择公司");
        }
        if (company.getMaxEmployeeNum() == null && company.getMaxShopNum() == null) {
            return R.error("请填写公司店铺、店铺员工数量");
        }
        CompanyAO updateCompany = new CompanyAO();
        updateCompany.setId(company.getId());
        updateCompany.setMaxShopNum(company.getMaxShopNum());
        updateCompany.setMaxEmployeeNum(company.getMaxEmployeeNum());
        companyService.updateById(updateCompany);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @RequiresPermissions({"merchant:company:delete"})
    public R delete(@RequestBody Integer[] ids) {
        if (ids != null && ids.length > 0) {
            companyService.deleteBatch(Arrays.asList(ids));
        }
        return R.ok();
    }

    /**
     * 获取当前登录账号权限范围的公司
     */
    @RequestMapping(value = "/getByUser")
    public R getByUser() {
        Long userId = getUserId();
        Wrapper<CompanyAO> wrapper = new EntityWrapper<>();
        wrapper.orderBy("id desc");
        String username = getUser().getUsername();
        // 公司管理员
        if (isCompanyRole()) {
            wrapper.eq("username", username);
        } else if (isEmployeeRole()) {
            // 当前登录用户为员工
            wrapper.where("id = (select company_id from t_employee where username = '" + username + "')");
        }
        List<CompanyAO> list = new ArrayList<>(companyService.selectList(wrapper));
        return R.ok().put("data", list);
    }
}
